<template>
	<view class="ve-list">
		<scroll-view :scroll-top="scrollTop" scroll-y style="height: 100%;width: 100%;" :scroll-with-animation="true"
			refresher-enabled :refresher-triggered="refreshStatus" :enable-back-to-top="true"
			@refresherrefresh="resetRefresh(true)" @scrolltolower="reachBottom">
			<view class="record-list" :style="{'padding-bottom': paddingBottom+'rpx'}">
				<view class="record-item" v-for="(record, index) in list" :key="record[key]">
					<slot name="item" :record="record"></slot>
				</view>
				<!-- 加载结束列表为空时展示 -->
				<ve-empty v-if="list.length== 0 && loadStatus == 'nomore'" />
				<!-- 底部加载状态 -->
				<ve-load-more v-else :status="loadStatus" bgColor="#F7F7F9" />
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		name: 've-list',
		props: {
			key: {
				type: String,
				default: 'id'
			},
			pageSize: {
				type: String,
				default: '10'
			},
			paddingBottom: {
				type: String,
				default: '60'
			},
			getList: Function
		},
		data() {
			return {
				pageNumber: 1,
				loadStatus: 'loading',
				refreshStatus: false,
				scrollTop: 0,
				list: []
			}
		},
		mounted() {
			this.getRecordList();
		},
		methods: {
			// 到顶部
			goTop(e) {
				this.scrollTop = -1;
				this.$nextTick(() => {
					this.scrollTop = 0
				});
			},
			reachBottom() {
				// nomore 直接返回
				if (this.loadStatus == 'nomore') return
				this.loadStatus = "loading"
				this.getRecordList()
			},
			// 下拉刷新(重置刷新)
			resetRefresh(pullDown = false) {
				this.pageNumber = 1
				if (pullDown) {
					this.refreshStatus = true
				}
				this.getRecordList()
			},
			// 页面数据
			async getRecordList() {
				const res = await this.getList({
					pageNumber: this.pageNumber,
					pageSize: this.pageSize
				})

				if (res.code == 200) {
					const {
						data,
						totalPage
					} = res.result;
					// 第一页list替换，否则追加
					if (this.pageNumber == 1) {
						this.list = data;
						this.loadStatus = 'loading'
						// 到顶部
						this.goTop()
						this.refreshStatus = false;
					} else {
						this.list = [...this.list, ...data];
					}
					// 最后一条判断
					if (this.pageNumber >= totalPage) {
						this.loadStatus = 'nomore'
					} else {
						this.pageNumber++
					}
				} else {
					uni.showToast({
						icon: 'none',
						title: res.message
					})
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.ve-list {
		width: 100%;
		height: 100%;
		
		.record-list {
			min-height: 100%;
		}
	}
</style>
